package com.wondertek.web.controller.task;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wondertek.common.base.Result;
import com.wondertek.service.entity.business.DevicePo;
import com.wondertek.service.sdk.iotdh.dto.req.DeviceListReq;
import com.wondertek.service.sdk.iotdh.dto.res.DevicePageRes;
import com.wondertek.service.sdk.iotdh.dto.res.DeviceRes;
import com.wondertek.service.sdk.iotdh.service.DhDeviceService;
import com.wondertek.service.service.business.DeviceService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 设备查询定时任务
 * @author: qinjianhui
 * @create: 2024-08-19 21:43
 **/
@Component
public class DeviceTask {
    @Resource
    private DeviceService deviceService;

    @Resource
    private DhDeviceService dhDeviceService;

    //@Scheduled(cron = "0 56 13 * * ?")
    @Scheduled(cron = "*/60 * * * * ?")
    public void start() {
        System.out.println("-----------"+new Date()+"设备更新状态定时任务开始");
        //1.先查询设备数据
        LambdaQueryWrapper<DevicePo> devicePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devicePoLambdaQueryWrapper.eq(DevicePo::getIsDelete,0);
        List<DevicePo> devicePoList = deviceService.list(devicePoLambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(devicePoList)){
            List<String> deviceCodes = devicePoList.stream().map(DevicePo::getDeviceCode).collect(Collectors.toList());
            //每10条一组
            double result = Math.ceil((double) deviceCodes.size() / 10);
            int count = (int)result;
            for(int i=0; i<count; i++){
                List<String> codes;
                if(i==count-1){
                    codes = deviceCodes.subList(i*10,deviceCodes.size());
                }else{
                    codes = deviceCodes.subList(i,(i+1)*10);
                }
                //2.查询大华接口获取设备状态
                DeviceListReq deviceListReq = new DeviceListReq();
                deviceListReq.setDeviceIds(codes);
                try {
                    Result<DevicePageRes> devicePageResResult = dhDeviceService.pageDevice(deviceListReq);
                    DevicePageRes devicePageRes = JSONObject.parseObject(String.valueOf(devicePageResResult.getData()),DevicePageRes.class);
                    if(devicePageRes!=null){
                        List<DeviceRes> records = devicePageRes.getRecords();
                        if (CollectionUtils.isEmpty(records)) continue;
                        //3.将设备状态插入数据库
                        for(DeviceRes deviceRes : records){
                            updateDeviceStatus(deviceRes.getStatus(), deviceRes.getDeviceId(), deviceRes.getDeviceSn());
                        }
                    }
                }catch (Exception e){
                    for(String code : codes){
                        DeviceListReq deviceListReq1 = new DeviceListReq();
                        List<String> ids = new ArrayList<>();
                        ids.add(code);
                        deviceListReq1.setDeviceIds(ids);
                        try{
                            Thread currentThread = Thread.currentThread();
                            currentThread.sleep(3000);
                            Result<DevicePageRes> devicePageResResult = dhDeviceService.pageDevice(deviceListReq1);
                            DevicePageRes devicePageRes = JSONObject.parseObject(String.valueOf(devicePageResResult.getData()),DevicePageRes.class);
                            if(devicePageRes!=null){
                                List<DeviceRes> records = devicePageRes.getRecords();
                                if (CollectionUtils.isEmpty(records)) continue;
                                DeviceRes deviceRes = records.get(0);
                                updateDeviceStatus(deviceRes.getStatus(), deviceRes.getDeviceId(), deviceRes.getDeviceSn());
                            }
                        }catch (Exception e1){
                            continue;
                        }
                    }
                }
            }
        }
        System.out.println("-----------"+new Date()+"设备更新状态定时任务结束");
    }

    /*
    * 统一处理设备状态更新
    * */
    private void updateDeviceStatus(Integer status, String deviceCode, String snCode){
        LambdaQueryWrapper<DevicePo> select = new LambdaQueryWrapper<>();
        select.eq(DevicePo::getDeviceCode,deviceCode);
        select.eq(DevicePo::getSnCode,snCode);
        List<DevicePo> list = deviceService.list(select);
        if (CollectionUtils.isNotEmpty(list)){
            DevicePo devicePo = list.get(0);
            if(status!=devicePo.getStatus()){
                devicePo.setStatus(status);
                deviceService.updateById(devicePo);
            }
        }
    }
}

